package com.seal.commons.query;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-06-21 12:13<br/>
 * @since JDK 1.8
 */
@Slf4j
@Data
public class QueryRequest implements Serializable, PageAble {

    private static final long serialVersionUID = 2648024170204419679L;

    private static final String PAGE_INDEX = "pageIndex";

    private static final String PAGE_SIZE = "pageSize";

    private static final String ROW_START = "rowStart";



    /**
     * 查询参数
     */
    private Map filters = new HashMap();

    /**
     * 查询参数
     */
    private Boolean singleQuery = false;


    /**
     * 排序列
     */
    private String sortColumn;

    /**
     * 排序方式，ASC：升序， DESC: 降序
     */
    private String sortDrection;

    /**
     * 页码
     */
    private int pageIndex = 1;

    /**
     * 每页行数
     */
    private int pageSize = 50;

    /**
     * 总笔数
     */
    private int totalNumber = 0;

    /**
     * 总页数
     */
    private int totalPages = 0;


    public void setPage(){
        filters.put(PAGE_INDEX, pageIndex + "");
        filters.put(PAGE_SIZE, pageSize + "");
        filters.put(ROW_START, (pageIndex-1) * pageSize + "");
    }


    @Override
    public int getPageIndex() {
        String page = getFilterParameterAsString(PAGE_INDEX);
        try{
            return (page == null || page.length() == 0) ? 1 : Integer.parseInt(page);
        }catch (NumberFormatException e){
            return 1;
        }
    }

    @Override
    public int getPageSize() {
        String page = getFilterParameterAsString(PAGE_SIZE);
        try{
            int pageSize =  (page == null || page.length() == 0) ? Integer.MAX_VALUE : Integer.parseInt(page);
            if(pageSize > 0){
                return pageSize;
            }
            return Integer.MAX_VALUE;
        }catch (NumberFormatException e){
            return Integer.MAX_VALUE;
        }
    }

    @Override
    public int getTotalNumber() {
        return totalNumber;
    }

    @Override
    public int getTotalPages() {
        return (((totalNumber - 1) / getPageSize()) + 1);
    }

    private String getFilterParameterAsString(String key) {
        Object parameter = filters.get(key);
        if (parameter != null){
            if (parameter instanceof String){
                return (String) parameter;
            }else{
                log.warn("Parameters contain the parameter '" + key + "' but it isn't String, as expected. It is a "
                            + parameter.getClass() + " with the value " + parameter, new ClassCastException());
            }
        }
        return null;
    }

    public void setTotalNumber(int totalNumber) {
        this.totalNumber = totalNumber;
    }
}